<?php

namespace app\admin\service;

/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/4/26
 * Time: 15:41
 */

use app\admin\model\Shop;
use \think\Db;
/**
 * 门店服务
 * Class ShopService
 * @package app\admin\service
 */
class ShopService
{

    protected $model;

    /**
     * ShopService constructor.
     */
    public function __construct()
    {
        $this->model = new Shop();
    }

    /**
     * @return ShopService
     */
    public static function instance()
    {
        return new self();
    }

    /**
     * 公共筛选
     * @return $this|Shop
     */
    public function filter()
    {
        $query = $this->model;
        $param = input();
        $where = [];
        //条件查询
        $startTime = empty($param['start_time']) ? 0 : strtotime($param['start_time']);
        $endTime = empty($param['end_time']) ? 0 : strtotime($param['end_time']);
        if (!empty($startTime) && !empty($endTime)) {
            $where['addtime'] = [['>= time', $startTime], ['<= time', $endTime]];
        } else {
            if (!empty($startTime)) {
                $where['addtime'] = ['>= time', $startTime];
            }
            if (!empty($endTime)) {
                $where['addtime'] = ['<= time', $endTime];
            }
        }
        $shopName = empty($param['shopName']) ? '' : $param['shopName'];
        if (!empty($shopName)) {
            $where['shopName'] = ['like', '%' . $shopName . '%'];
        }
        //默认未删除的店铺
        $query = $query->where($where);

        return $query;
    }

    /**
     * 获取一个门店
     * @param $shopId
     * @return array|false|\PDOStatement|string|\think\Model
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getOneShop($shopId)
    {
        return $this->filter()->where(['shopId' => $shopId])->find();
    }

    /**
     * 添加店铺
     * @return int|string
     */
    public function add()
    {
        $param = input();
        //dump($param['pic']);exit;
        $arr = [
            'shopName' => $param['shopName'],
            'address' => $param['address'],
            'staffId' => $param['staffId'],
            'lat' => $param['lat'],
            'lng' => $param['lng'],
            'status' => $param['status'],
            'type' => $param['type'],
            'addtime' => date('Y-m-d H:i:s'),
        ];
        $shopId=$this->model->insertGetId($arr);

        //图片
        $pics=explode(",",$param['pic']);
        foreach ($pics as $k => $v) {
            $data=[
                'pic'=>$v,
                'shopId'=>$shopId,
                'addtime'=>date('Y-m-d H:i:s')
            ];
            db::name('shop_pic')->insert($data);
        }

        //默认上下班
        $arr=[
            'numbers'=>0,
            'serveringNumbers'=>0,
            'waitingServer'=>0,
            'shopid'=>$shopId,
            'addTime'=>date('Y-m-d H:i:s')
        ];
        db::name('shop_server')->insert($arr);
        //商品
        $ids=explode(",",$param['product']);
        $rs=db::name('commodity')->where('id','in',$ids)->field('id,name')->select();
        $i=[];
        foreach ($rs as $k => $v) {
            $arr=[
                'name'=>$v['name'],
                'shopId'=>$shopId,
                'shopMoney'=>$param['shopMoney'.$v['id']],
                'discount'=>$param['discount'.$v['id']],
                'commondityId'=>$v['id'],
                'addtime'=>date('Y-m-d H:i:s'),
            ];
            db::name('shop_config')->insert($arr);
            $i[$k]=$arr;
        }
        $data=[
            'action'=>'shopConfigAdd',
            'content'=>json_encode($i),
            'time'=>date('Y-m-d H:i:s'),
        ];
        db::name('log')->insert($data);
        return true;
    }

    /**
     * 获取门店列表
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public function getList()
    {
        $shopList = $this->filter()->paginate(input('page_size', 10));
        return $shopList;
    }

    /**
     * 获取服务列表
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public function commodity()
    {
        return db::name('commodity')->field('id,name')->select();
    }

    /**
     * 修改店铺信息
     * @param $shopId int
     * @return array
     */
    public function edit($shopId)
    {
        $param = input();
        $updateArray = [
            'address' => input('address', ''),
            'staffId' => $param['staffId'],
            'status' => input('status', Shop::STATUS_TWO),
            'type' => input('type', Shop::IS_UP_TWO),
            'lat' => input('lat', 0),
            'lng' => input('lng', 0),
        ];
        $this->model->where(['shopId' => $shopId])->update($updateArray);

        //图片
        $pics=explode(",",$param['pic']);
        foreach ($pics as $k => $v) {
            $re=db::name('shop_pic')->where('pic',$v)->value('id');
            if(empty($re)){
                $data=[
                    'pic'=>$v,
                    'shopId'=>$shopId,
                    'addtime'=>date('Y-m-d H:i:s')
                ];
                db::name('shop_pic')->insert($data);
            }
        }

        $ids=explode(",",$param['product']);
        $rs=db::name('commodity')->where('id','in',$ids)->field('id,name')->select();
        $aa=db::name('shop_config')->where('commondityId','not in',$ids)->where('shopId',$shopId)->delete();
        $i=[];
        foreach ($rs as $k => $v) {
            $id=db::name('shop_config')->where('commondityId',$v['id'])->where('shopId',$shopId)->value('id');
            if(empty($id)){
                $arr=[
                    'name'=>$v['name'],
                    'shopId'=>$shopId,
                    'shopMoney'=>$param['shopMoney'.$v['id']],
                    'discount'=>$param['discount'.$v['id']],
                    'commondityId'=>$v['id'],
                    'addtime'=>date('Y-m-d H:i:s'),
                ];
                db::name('shop_config')->insert($arr);
                $i[$k]=$arr;
            }else{
                $arr=[
                    'shopMoney'=>$param['shopMoney'.$v['id']],
                    'discount'=>$param['discount'.$v['id']],
                ];
                $i[$k]=$arr;
                db::name('shop_config')->where('commondityId',$v['id'])->where('shopId',$shopId)->update($arr);

            }
        }
            $data=[
            'action'=>'shopConfigAdd',
            'content'=>json_encode($i),
            'time'=>date('Y-m-d H:i:s'),
            ];
            $rs=db::name('log')->insert($data);
        return ['code' => 1, 'msg' => '修改成功'];
    }

    /**
     * 用于修改门店信息
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function update()
    {
        $shop = $this->getOneShop(input('shopId', 0));
        if (!$shop) {
            return ['code' => -1, 'msg' => '店铺不存在'];
        }
        $value = input('value') == 1 ? 2 : 1;
        $re = $this->model->where(['shopId' => input('shopId')])->update([input('type') => $value]);
        if ($re === false) {
            return ['code' => -1, 'msg' => '修改失败，请联系管理员'];
        }

        return ['code' => 1, 'msg' => '修改成功'];
    }

    /**
     * 删除店铺
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function del()
    {
        $shop = $this->getOneShop(input('shopId', 0));
        if (!$shop) {
            return ['code' => -1, 'msg' => '店铺不存在'];
        }
        db::name('staff')->where('userId',$shop['staffId'])->update(['type'=>1]);
        $re = $shop->where(['shopId' => input('shopId')])->delete();
        db::name('shop_config')->where('shopId',input('shopId'))->delete();
        if ($re !== false) {
            return ['code' => 1, 'msg' => '删除成功'];
        } else {
            return ['code' => -1, 'msg' => '删除失败，请联系管理员'];
        }
    }
}

